﻿using System.ComponentModel;
using System.Text;

namespace pinlib.Kernel32
{
    /// <summary>
    /// Functions dealing with the Windows registry
    /// </summary>
    /// <seealso>http://msdn.microsoft.com/en-us/library/ms724875(v=VS.85).aspx</seealso>
    public static class RegistryM
    {
        /// <summary>
        /// Retrieves a string from the specified section in an initialization file
        /// </summary>
        /// <param name="fileName">full path to the .ini file to read</param>
        /// <param name="section">The name of the section containing the key name</param>
        /// <param name="key">The name of the key whose associated string is to be retrieved</param>
        /// <returns>corresponding value, or null if not found</returns>
        /// <example>
        /// This example demonstrates how to get the "ID" key from the "Software" section. The assumed filename is "keys.ini"
        /// [Software]
        /// ID=1234-5432
        ///   <code>
        /// string iniPath = "C:\keys.ini"
        /// string myVal = GetPrivateProfileStringM(iniPath, "Software", "ID");
        /// Debug.WriteLine("Software Key: " + myVal);
        ///   </code>
        ///   </example>
        ///   
        /// <exception cref="System.ComponentModel.Win32Exception">Throws an exception for a Win32 error code.</exception>
        public static string GetPrivateProfileStringM(string fileName, string section, string key)
        {
            StringBuilder sb = new StringBuilder(10);
            try
            {
                Kernel32.GetPrivateProfileString(section, key, null, sb, sb.Capacity, fileName);
                return sb.Length == 0 ? null : sb.ToString();
            }
            catch (Win32Exception err)
            {
                throw new Win32Exception(err.Message, err.GetBaseException());
            }
        }
    }
}